<template>
  <!-- <div>
    <h1>我是User列表</h1>
  </div> -->
  <SonUserTable>
    <template #search>
      <SonSousuo @onSearchSubmit="onSearchSubmit" :searchData="searchData"></SonSousuo>
    </template>
    <template #addItem>
      <Sonadd @addItemHandler="addItemHandler"></Sonadd>
    </template>
    <template #table>
      <SonTable :tableData="tableData" @handle-click="handleClick" @deldata="deldata"></SonTable>
    </template>
    <template #fenye>
      <SonFenye @updateyema="updateyema" :fenyeqi="fenyeqi"></SonFenye>
    </template>
    <template #editrloe>
      <Sonxiugai
        v-model="isEditDialogVisible"
        :ruleFormInfo="ruleFormInfo"
        :rules="rules"
        :ruleFormRef="ruleFormRef"
        @resetForm="resetForm"
        @submitForm="submitForm"
        :ruleForm="ruleForm"
        ref="createxinxi"
      ></Sonxiugai>
    </template>
  </SonUserTable>
</template>

<script setup lang="ts">
import {
  editRole,
  delRole,
  addRole,
  type RolesType,
  requestGetRolesPage
} from '@/views/study5/service/study1/demo3'
import Sonxiugai from './SonDemo/Sonxiugai.vue'
import SonSousuo from './SonDemo/SonSousuo.vue'
import Sonadd from './SonDemo/Sonadd.vue'
import SonTable from './SonDemo/SonTable.vue'
import SonFenye from './SonDemo/SonFenye.vue'
import SonUserTable from './SonDemo/SonUserTable.vue'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
const isEditDialogVisible = ref(false)
const tableData = ref<RolesType[]>()
const ruleFormRef = ref<FormInstance>()

let ruleForm = ref<RolesType>({
  code: '',
  createTime: '',
  name: '',
  sort: 1,
  status: 1
})

const ruleFormInfo = ref<{
  type: 'add' | 'edit' | 'del'
  title: string
}>({
  type: 'edit',
  title: '修改信息'
})

const fenyeqi = ref({
  yema: 1,
  maxyema: 13,
  zongyema: 0
})

const rules = reactive<FormRules<RolesType>>({
  id: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  name: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  code: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  status: [{ required: true, message: '不可以为空', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.value.id = Number(ruleForm.value.id)

      // // 添加
      if (ruleFormInfo.value.type === 'add') {
        // 请求
        const res = await addRole(ruleForm.value)
        // console.log(res, '999999')
        if (res.code !== '2000') {
          ElMessage.error('数据添加失败')
          return
        }
        ElMessage.success('数据添加成功')
      }

      // 修改

      // ruleForm.value.id = Number(ruleForm.value.id)
      if (ruleFormInfo.value.type === 'edit') {
        const res = await editRole(ruleForm.value.id, ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据修改失败')
          return
        }
        ElMessage.success('数据修改成功')
        // 重置表单
        formEl.resetFields()
      }

      // 删除
      if (ruleFormInfo.value.type === 'del') {
        const res = await delRole(ruleForm.value.id)
        if (res.code !== '2000') {
          ElMessage.error('数据删除失败')
          return
        }
        ElMessage.success('数据删除成功')
      }

      // 关闭模态框
      isEditDialogVisible.value = false

      // 再次重新渲染数据
      getPageData()

      // 重置表单
      formEl.resetFields()
      // console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// if (isEditDialogVisible.value) {
//   // 重置表单
//   createxinxi.value?.createxinxi(ruleFormRef.value)
// }

// 删除
const deldata = (row: any) => {
  ruleFormInfo.value = {
    type: 'del',
    title: '删除信息'
  }
  ruleForm.value.id = row.id
  isEditDialogVisible.value = true
}

// 添加数据
const addItemHandler = () => {
  // 重置表单
  // createxinxi.value?.createxinxi(ruleFormRef.value)
  ruleFormRef.value?.resetFields()
  ruleFormInfo.value = {
    type: 'add',
    title: '添加信息'
  }
  // ruleFormRef.value
  // ruleFormRef.value?.resetFields()
  // 清空验证
  ruleFormRef.value?.clearValidate()

  isEditDialogVisible.value = true
}

// 修改
const handleClick = (row: RolesType) => {
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改信息'
  }

  console.log(row, 'rowrowrow')

  // ruleForm.value.code = row.code
  // ruleForm.value.createTime = row.createTime
  // ruleForm.value.id = row.id
  // ruleForm.value.name = row.name
  // ruleForm.value.sort = row.sort
  // ruleForm.value.status = row.status

  Object.assign(ruleForm.value, JSON.parse(JSON.stringify(row)))
  isEditDialogVisible.value = true
}

const getPageData = async () => {
  const res = await requestGetRolesPage({
    pageNum: fenyeqi.value.yema,
    pageSize: fenyeqi.value.maxyema
  })
  console.log(res.data.list)
  tableData.value = res.data.list
  fenyeqi.value.zongyema = res.data.total
}
onMounted(() => {
  getPageData()
})

const updateyema = (pageNum: number, pageSize: number) => {
  fenyeqi.value.yema = pageNum
  fenyeqi.value.maxyema = pageSize
  getPageData()
}

const searchData = reactive({
  id: '',
  name: '',
  status: ''
})
// console.log(searchData.status)

// 检索
const onSearchSubmit = () => {
  if (searchData.id === '' && searchData.name === '' && searchData.status === undefined) {
    getPageData()
  } else if (tableData.value) {
    tableData.value = tableData.value.filter((item) => {
      const idMatch = searchData.id ? item.id === Number(searchData.id) : true
      const nameMatch = searchData.name ? item.name === searchData.name : true
      const statusMatch = searchData.status ? item.status === Number(searchData.status) : true
      return idMatch && nameMatch && statusMatch
    })
  }
}
// watch(
//   () => searchData.status,
//   (newVAl) => {
//     console.log(newVAl)
//   }
// )

// const onSearchSubmit = () => {
//   if (Object.values(searchData).every((value) => value === '')) {
//     getPageData()
//   } else if (tableData.value) {
//     tableData.value = tableData.value.filter((item) => {
//       const idMatch = searchData.id ? item.id === Number(searchData.id) : true
//       const nameMatch = searchData.name ? item.name === searchData.name : true
//       const statusMatch = searchData.status ? item.status === Number(searchData.status) : true
//       return idMatch && nameMatch && statusMatch
//     })
//   }
// }
</script>

<style lang="scss" scoped>
// .el-table {
//   height: calc(100vh - 200px);
// }
</style>
